package sdu.attendancechecker.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sdu.attendancechecker.dto.Teacher;
import sdu.attendancechecker.services.TeacherService;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher dispatcher = req.getRequestDispatcher("login.jsp");
		dispatcher.forward(req, resp);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String email = (String) request.getParameter("email");
		String password = (String) request.getParameter("password");
		Teacher t = TeacherService.login(email, password);
		if (t == null) {
			request.setAttribute("errorText", "Invalid email or password");
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("login.jsp");
			dispatcher.forward(request, response);
		} else {
			// Teacher successfully logged in
			System.out.println("Teacher successfully logged in");
			HttpSession session = request.getSession();
			session.setAttribute("teacher", t);
//			RequestDispatcher dispatcher = request
//					.getRequestDispatcher("subjects");
//			dispatcher.forward(request, response);
			response.sendRedirect(getServletContext().getContextPath());
		}
	}

}
